﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using BLL;

public partial class Report_KSXS : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Check.CheckPermission("900300");
        if (!IsPostBack)
        {
            List<Model.ORDERFROM> lst = new BLL.ORDERFROM().GetAllList(false);
            drpOrderFrom.Items.Add(new ListItem("全部", ""));
            foreach (Model.ORDERFROM order in lst)
            {
                drpOrderFrom.Items.Add(new ListItem(order.OF_NAME, order.OF_CODE));
            }
            string kwdm = ConfigurationManager.AppSettings["kwdm"];
            string cpkwdm = ConfigurationManager.AppSettings["cpkwdm"];
            if (kwdm == cpkwdm)
            {
                ListItem[] items ={new ListItem("全部","全部"),
                              new ListItem(kwdm,kwdm),
            };
                drpKW.Items.AddRange(items);
            }
            else
            {
                ListItem[] items1 ={new ListItem("全部","全部"),
                              new ListItem(kwdm,kwdm),
                              new ListItem(cpkwdm,cpkwdm)
            };
                drpKW.Items.AddRange(items1);
            }

            txtSP.Attributes.Add("onclick", "SearchProduct_Report('../')");
        }
    }


    protected void btnExport_Click(object sender, EventArgs e)
    {
        if ((txtStart.Text.Trim().Length < 1 || txtEnd.Text.Trim().Length < 1) && (txtDate1.Text.Trim().Length < 1 || txtDate2.Text.Trim().Length < 1) && (txtDate3.Text.Trim().Length < 1 || txtDate4.Text.Trim().Length < 1))
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert(\"请至少输入一个起止日期\")", true);
            return;
        }
        if (HttpContext.Current.Request.Form.Get("txtSP").Length > 8000)
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert(\"选择产品过多,产品代码字符串长度之和不能超过8000字符\")", true);
            return;
        }
        try
        {
            Bind(1); //导出excel
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert(\"统计出错\")", true);
            return;
        }
    }


    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if ((txtStart.Text.Trim().Length < 1 || txtEnd.Text.Trim().Length < 1) && (txtDate1.Text.Trim().Length < 1 || txtDate2.Text.Trim().Length < 1) && (txtDate3.Text.Trim().Length < 1 || txtDate4.Text.Trim().Length < 1))
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert(\"请至少输入一个起止日期\")", true);
            return;
        }
        if (HttpContext.Current.Request.Form.Get("txtSP").Length > 8000)
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert(\"选择产品过多,产品代码字符串长度之和不能超过8000字符\")", true);
            return;
        }
        try
        {
            Bind(0);
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert(\"统计出错\")", true);
            return;
        }
    }

    /// <summary>
    /// DataTable导出Excel
    /// </summary>
    /// <param name="dtData"></param>
    public static void DataTable2Excel(System.Data.DataTable dtData)
    {
        System.Web.UI.WebControls.DataGrid dgExport = null;
        System.Web.HttpContext curContext = System.Web.HttpContext.Current;
        System.IO.StringWriter strWriter = null;
        System.Web.UI.HtmlTextWriter htmlWriter = null;

        if (dtData != null)
        {
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
            curContext.Response.Charset = "";

            dtData.Rows.RemoveAt(0);
            strWriter = new System.IO.StringWriter();
            htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

            dgExport = new System.Web.UI.WebControls.DataGrid();

            //dtData.Columns.Add("发放状态");
            ////dtData.Columns.Add("财务审核");
            ////dtData.Columns.Add("结算");


            //dtData.Columns["id_PageRowID"].ColumnName = "序号";
            dtData.Columns["SPDM"].ColumnName = "款号";
            dtData.Columns["SPMC"].ColumnName = "商品名称";
            dtData.Columns["QTY"].ColumnName = "销售数量";
            dtData.Columns["QTY_RATE"].ColumnName = "占比（数量）";

            dtData.Columns["AMT"].ColumnName = "销售金额";
            dtData.Columns["AMT_RATE"].ColumnName = "占比（金额）";
            dtData.Columns["AVGPRICE"].ColumnName = "平均单价";
            dtData.Columns["KW"].ColumnName = "仓库";
            dtData.Columns["SL"].ColumnName = "库存量";
            dtData.Columns["SL3"].ColumnName = "可用量";
            dtData.Columns["PERIOD"].ColumnName = "周转期";
            //for (int i = 0; i < dtData.Rows.Count; i++)
            //{
            //    //dtData.Rows[i]["发货/入库"] = dtData.Rows[i]["SendOrReceive"].ToString() == "1" ? "已发货" : "未发货"; 

            //    dtData.Rows[i]["发放状态"] = dtData.Rows[i]["SENDFLAG"].ToString() == "1" ? "已发放" : "未发放";

            //}
            //////移除列

            //dtData.Columns.Remove(dtData.Columns["SENDFLAG"]); 

            dgExport.DataSource = dtData.DefaultView;
            dgExport.AllowPaging = false;
            dgExport.DataBind();

            dgExport.RenderControl(htmlWriter);
            curContext.Response.Write(strWriter.ToString());
            curContext.Response.End();
        }
    } 


    private void Bind(int pageIndex)
    {
        if (HttpContext.Current.Request.Form.Get("txtSP").Length <= 8000)
        {
            hdSPDM.Value = HttpContext.Current.Request.Form.Get("txtSP");
        }
        #region 组织日期条件
        string date="";
        if (txtStart.Text.Trim().Length > 0||txtEnd.Text.Trim().Length>0)
        { date += " AND ORDER_CREATEDATE between '" + txtStart.Text.Trim() + "' and '" + DateTime.Parse(txtEnd.Text.Trim()).AddDays(1) + "'"; }
        if (txtDate1.Text.Trim().Length > 0 || txtDate2.Text.Trim().Length > 0)
        { date += " AND ORDER_CHECKDATE between '" + txtDate1.Text.Trim() + "' and '" + DateTime.Parse(txtDate2.Text.Trim()).AddDays(1) + "'"; }
        if (txtDate3.Text.Trim().Length > 0 || txtDate4.Text.Trim().Length > 0)
        { date += " AND ORDER_SENDDATE between '" + txtDate3.Text.Trim() + "' and '" + DateTime.Parse(txtDate4.Text.Trim()).AddDays(1) + "'"; }
        #endregion
        DataSet ds = new BLL.ReportBL.KSXSStatistics().GetKSXS(date,"", drpOrderFrom.SelectedValue, drpKW.SelectedValue, hdSPDM.Value);
     

        if (ds.Tables[0].Rows.Count > 1)
        {
            if (pageIndex!=0)  //导出excel
            {

                DataTable2Excel(ds.Tables[0]);
            }

            DataView view = new DataView(ds.Tables[0], "SPDM<>''", "AMT DESC", DataViewRowState.CurrentRows);
            grdKSXS.DataSource = view;
            grdKSXS.DataBind();
            grdKSXS.PageIndex = pageIndex;
            DataRow dr = ds.Tables[0].Select("SPDM=''")[0];
            grdKSXS.FooterRow.Cells[3].Text = string.Format("{0:N0}", decimal.Parse(dr["QTY"].ToString()));
            grdKSXS.FooterRow.Cells[4].Text = string.Empty;
            grdKSXS.FooterRow.Cells[5].Text = string.Format("{0:N2}", decimal.Parse(dr["AMT"].ToString()));
            grdKSXS.FooterRow.Cells[6].Text = string.Empty;
            //grdKSXS.FooterRow.Cells[7].Text = string.Format("{0:N2}", decimal.Parse(dr["AVGPRICE"].ToString()));
            grdKSXS.FooterRow.Cells[9].Text = string.Format("{0:N0}", decimal.Parse(dr["SL"].ToString()));
            grdKSXS.FooterRow.Cells[10].Text = string.Format("{0:N0}", decimal.Parse(dr["SL3"].ToString()));
            //grdKSXS.FooterRow.Cells[11].Text = string.Format("{0:N2}", decimal.Parse(dr["PERIOD"].ToString()));
        }
    }
}
